import CommonModal from "@/components/CommonModal";
import Typography from "@/views/components/Typography";
import CommonLoading from "@/components/CommonLoading";
import CommonTable from "@/components/CommonTable";
import { useEffect, useState } from "react";
import { Button, message } from "antd";
import { aftersalelogDetail, aftersalelogDetailCount } from "../../services";
import { handleExportExcel } from '@/utils/utils.jsx';
import { stringify } from 'qs';

/** 处理结果 */
function AgreeBuyerRefund(props) {
	const { logId, handleCancel } = props;
	const [loading, setLoading] = useState(false);
	const [logData, setLogData] = useState({});
	const [open, setOpen] = useState(false);
	const { resultList = [], countStatics = {} } = logData;

	const columns = [
		{
			title: "售后单号",
			dataIndex: "afterSaleSn",
			width: 120
		},
		{
			title: "处理结果",
			dataIndex: "state",
			width: 120,
			render: text => text == 1 ? '成功' : '失败'
		},
		{
			title: "失败原因",
			dataIndex: "failReason",
			width: 120
		}
	];

	useEffect(() => {
		setOpen(true);
		initData();
	}, []);

	//获取展示信息
	const initData = async () => {
		setLoading(true);
		const query1 = aftersalelogDetail({ logId });
		const query2 = aftersalelogDetailCount({ logId });
		Promise.all([query1, query2]).then(res => {
			setLoading(false);
			const obj = {};
			if (res[0].success) {
				obj.resultList = res[0].data.records;
			}
			if (res[1].success) {
				obj.countStatics = res[1].data;
			}
			setLogData(obj);
		});
	};

	//导出
	const handleExport = async () => {
		if(countStatics.operationFail > 0) {
			setLoading(true);
			const params = {
				logId
			}
			handleExportExcel(`/new-oms-ec/aftersaleoperationlog/detailExport?${stringify(params)}`, '失败原因.xlsx', () => {
				setLoading(false);
			})
		} else {
			message.info('没有可导出的数据');
		}
	
	};

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		handleCancel();
	};

	const TableProps = {
		data: resultList,
		columns
	};

	const footer = (
		<div>
			<Button onClick={onCancel}>关闭</Button>
			<Button type="primary" onClick={handleExport}>
				导出失败订单
			</Button>
		</div>
	);

	return (
		<CommonModal title="处理结果" footer={footer} afterClose={afterClose} open={open} width="589px" onCancel={onCancel}>
			<div style={{ margin: "12px 0" }}>
				处理成功的售后单数：<Typography type="error">{countStatics.operationSuccess}</Typography>
			</div>
			<div style={{ margin: "12px 0" }}>
				处理失败的售后单数：<Typography type="error">{countStatics.operationFail}</Typography>
			</div>
			<CommonTable {...TableProps} />
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default AgreeBuyerRefund;
